const mixin = require('../../../mixins');

// const { mfutil } = getApp();
Component({
	behaviors: [mixin],
	data: {
		currIndex: 0,
		bottomIndex: 0,
		cornerMarkerObj: {
			left: [],
			right: []
		},
		opacity: 1,
		duration: 500,
		transformOrigin: '0 0',
		bottleAndTextData: {}
	},
	properties: {
		mf_data: Object,
	},
	pageLifetimes: {
		show: function() {
			if (!this.timer) {
				this.autoPlay()
			}
		},
		hide: function() {
			clearInterval(this.timer)
			this.timer = null
		},
	},
	attached() {
		this.initCornerMarker();
		this.initOrigin();
		this.autoPlay()
		this.setData({
			bottleAndTextData: this.properties.mf_data.children[this.data.currIndex]
		})
	},
	observers: {},
	ready() {},
	methods: {
		autoPlay() {
			const {
				autoPlay,
				autoPlayInterval = 3000
			} = this.properties.mf_data;
			if (autoPlay) {
				this.timer = setInterval(() => {
					this.handleTouchEnd(-1);
				}, autoPlayInterval);
			}
		},
		// 初始化异形轮播的缩放中心
		initOrigin() {
			const {
				alignMent
			} = this.properties.mf_data;
			let transformOrigin;
			switch (alignMent) {
				case "底对齐":
					transformOrigin = '50% 100%'
					break;
				case "居中":
					transformOrigin = '50% 50%'
					break;
				case "上对齐":
					transformOrigin = '50% 0%'
					break;
				default:
					break;
			}
			this.setData({
				transformOrigin
			})
		},
		initCornerMarker() {
			const {
				cornerMarker,
				children
			} = this.properties.mf_data;
			if (!cornerMarker) return;
			const {
				currIndex
			} = this.data;
			this.setData({
				cornerMarkerObj: {
					left: String(currIndex + 1).split(""),
					right: String(children.length).split(""),
				}
			})
		},
		onChange(event) {
			const {
				current,
				isChanging
			} = event.detail;
			if (!isChanging) {
				this.setData({
					currIndex: current,
					bottomIndex: current,
					opacity: 0
				}, () => {
					this.initCornerMarker();
					let that = this
					setTimeout(() => {
						that.setData({
							bottleAndTextData: that.properties.mf_data.children[
								current],
							opacity: 1
						})
					}, 300)

				})
			}
		},
		changeTo(_index) {
			this.onChange({
				detail: {
					current: _index
				}
			})
      this.handleTrack(_index);
		},
    // 埋点信息筛选
    async handleTrack(index){
      const _trackingParams = await this.filterUtoolsByKey(this.properties.mf_data.children[index],'trackingParams');
      if(_trackingParams){
        //  首页神策埋点 首页轮播/系列甄选
        if (this.properties.mf_data && (this.properties.mf_data.label1 == '首屏swiper' || this.properties.mf_data.label1 == '系列甄选')) {
          const _tag = this.properties.mf_data.children[index];
          const res = _tag.children.find(el => el.type === "hotSpace");
          if (res && res.trackingParams) {
            let _trackData = JSON.parse(res.trackingParams);
            _trackData.name = "BannerExposure";
            _trackData.type = "view";
            this.triggerEvent('triggerComponent', {
              data: {
                trackData: JSON.stringify(_trackData),
                type: "track"
              }
            }, {
              bubbles: true,
              composed: true
            });
            return;
          }
        }
        this.triggerEvent('triggerComponent', {
          data: {
            trackData: _trackingParams,
            type: "track"
          }
        }, {
          bubbles: true,
          composed: true
        });
      }
    },
		navigationRight() {
			let {
				currIndex
			} = this.data;
			let index = currIndex < (this.properties.mf_data.children.length - 1) ? currIndex + 1 : 0;
			this.changeTo(index)
		},
		navigationLeft() {
			let {
				currIndex
			} = this.data;
			let index = currIndex > 0 ? currIndex - 1 : this.properties.mf_data.children.length - 1;
			this.changeTo(index)
		},
		touchStart(e) {
			const {
				clientX,
				clientY
			} = e.changedTouches[0];
			// getCurrentPages()[0].$vm.setUtoolsP(false)
			this.startX = clientX;
			this.startY = clientY
		},
		touchMove(e) {
			const {
				clientX ,
				clientY
			} = e.changedTouches[0];

			let y = Math.abs(this.startY -clientY)
			let x = Math.abs(this.startX -clientX)
			if(x>y){
				// this.startY =996
				getCurrentPages()[0].$vm.setUtoolsP(false)
			}
		},
		touchEnd(e) {
			if (Date.now() - this.startTime < this.data.duration) return; // 如果两次触发的时间小于动画时间的话，不进行再次触发
			const {
				clientX
			} = e.changedTouches[0];
			const result = clientX - this.startX;
			if (Math.abs(result) < 40) {
				return
			}
			clearInterval(this.timer)
			this.timer = null
			this.startTime = Date.now(); // 当前动画触发的开始时间
			this.handleTouchEnd(result);
			const {
				autoPlay
			} = this.properties.mf_data;
			if (autoPlay && !this.timer) {
				setTimeout(() => {
					this.autoPlay()
				}, 500)
			}
			getCurrentPages()[0].$vm.setUtoolsP(true)
		},
		// 连滑开关
		timerTouch(time = 200) {
			this.switch = true;
			setTimeout(() => {
				this.switch = false;
			}, time)
		},
		// 处理滑动结束后的事情
		handleTouchEnd(result) {
			let {
				currIndex
			} = this.data;
			const {
				children = []
			} = this.properties.mf_data;
			let index = Number(currIndex);
			// 滑动滚动需要判断边界值
			if (result > 0) {
				if (index === 0) {
					// 边界值判断，最左边
					this.setData({
						currIndex: index - 1,
						bottomIndex: children.length - 1,
						opacity: 0
					}, () => {
						setTimeout(() => {
							this.setData({
								currIndex: children.length - 1,
								duration: 0
							}, () => {
								// 状态重置好之后，把动画时间调整为正常的时间
								setTimeout(() => {
									this.setData({
										duration: 500
									})
								}, 16.7)
								let that = this
								setTimeout(() => {
									that.setData({
										bottleAndTextData: that
											.properties.mf_data
											.children[that.data
												.currIndex],
										opacity: 1
									});
                  that.handleTrack(that.data.currIndex);
								}, 300)
							})
						}, this.data.duration)

					})
					return
				} else {
					index = index - 1;
				}
			} else {
				if (index === children.length - 1) {
					// 边界值判断，最右边
					this.setData({
						currIndex: index + 1,
						bottomIndex: 0,
						opacity: 0
					}, () => {
						setTimeout(() => {
							this.setData({
								currIndex: 0,
								duration: 0
							}, () => {
								// 状态重置好之后，把动画时间调整为正常的时间
								setTimeout(() => {
									this.setData({
										duration: 500
									})
								}, 16.7)
								let that = this
								setTimeout(() => {
									that.setData({
										bottleAndTextData: that
											.properties.mf_data
											.children[that.data
												.currIndex],
										opacity: 1
									})
                  that.handleTrack(that.data.currIndex);
								}, 300)
							})
						}, this.data.duration)
					})
					return
				} else {
					index = index + 1;
				}
			}
			this.changeTo(index);
		},
    //  筛选utools json中的商品列表对象
    async filterUtoolsByKey(data,key){
      try{
        if(data && data[key]) return data[key];
        if(data && data.children && data.children.length){
          for(let i=0;i<data.children.length;i++){
            if(data.children[i]){
              const res = await this.filterUtoolsByKey(data.children[i], key);
              if(res) return res;
            }
          }
        }
        return false;
      }catch(e){}
    },
	},
});
